﻿/*
Copyright (c) 2009 Vratislav Cermak (vratacermak@gmail.com)
 
This file is part of TeachMe Project. See http://code.google.com/p/teach-me for more information.
 
TeachMe is an open source project. Using of TeachMe is free of charge.
It is distributed under GNU General Public License version 3 (GPLv3).
GPLv3 can be found at http://www.gnu.org/licenses/gpl.html.
 
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

using System;
using System.IO;

namespace TeachMe.Application
{
    public class TemporaryContentManager
    {
        private const string Prefix = "TeachMe-";
        private readonly string _rootTempDirectory;

        public TemporaryContentManager()
        {
            Clean();

            _rootTempDirectory = Path.Combine(Path.GetTempPath(), Prefix + Guid.NewGuid());

            Directory.CreateDirectory(_rootTempDirectory);
        }

        public string CreateTempDirectory()
        {
            string result = Path.Combine(_rootTempDirectory, Guid.NewGuid().ToString());

            Directory.CreateDirectory(result);

            return result;
        }

        private static void Clean()
        {
            string[] directories = Directory.GetDirectories(Path.GetTempPath(), Prefix + "*", SearchOption.TopDirectoryOnly);

            foreach (string directory in directories)
            {
                try
                {
                    Directory.Delete(directory, true);
                }
                catch (Exception exception)
                {
                    Logging.Error(typeof(TemporaryContentManager), exception, "Temporary directory can not be deleted '{0}'.", directory);
                }
            }
        }
    }
}
